<?php

namespace MyLogger\Handlers;

use MyLogger\Formatters\FormatterInterface;
use MyLogger\Logger;

class StreamHandler implements HandlerInterface
{
    protected $stream;
    protected $level;
    protected $formatter;
    protected $filePermission;
    protected $url;

    public function __construct(
        $stream, 
        int $level = Logger::DEBUG, 
        FormatterInterface $formatter = null,
        int $filePermission = 0644
    ) {
        $this->level = $level;
        $this->filePermission = $filePermission;
        
        if (is_resource($stream)) {
            $this->stream = $stream;
            $this->url = '';
        } elseif (is_string($stream)) {
            $this->url = $stream;
            $this->openStream($stream);
        } else {
            throw new \InvalidArgumentException('Invalid stream provided');
        }
        
        $this->formatter = $formatter ?: new \MyLogger\Formatters\LineFormatter();
    }

    protected function openStream(string $path)
    {
        $dir = dirname($path);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        
        $this->stream = fopen($path, 'a');
        if ($this->filePermission !== null) {
            @chmod($path, $this->filePermission);
        }
    }

    public function setFormatter(FormatterInterface $formatter)
    {
        $this->formatter = $formatter;
    }

    public function handle(array $record): bool
    {
        if ($record['level'] < $this->level) {
            return false;
        }
        
        $formatted = $this->formatter->format($record);
        fwrite($this->stream, $formatted);
        
        return true;
    }
    
    public function close()
    {
        if (is_resource($this->stream)) {
            fclose($this->stream);
        }
    }
    
    public function __destruct()
    {
        $this->close();
    }
}